package com.ly.dict.core;

import com.knziha.plod.dictionary.mdict;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Init;
import org.noear.solon.annotation.Inject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Component
@Slf4j
public class MdictFactory {

    @Inject(value = "${solon.dict-path}")
    private String dataPath;

    private static List<Map<String, mdict>> mdicts = new ArrayList<>();

    public void addMdict(String name, mdict mdict) {
        Map<String, mdict> map = new HashMap<>();
        map.put(name, mdict);
        mdicts.add(map);
    }

    /**
     * 初始化词典列表
     *
     * @author leiyuan
     * @since 2025/4/20
     */
    @Init
    public void initMict() {
        File file = new File(dataPath);
        File[] files = file.listFiles();
        for (File f : files) {
            if (f.getName().endsWith(".mdx")) {
                try {
                    mdict md = new mdict(f.getAbsolutePath());
                    addMdict(f.getName(), md);
                } catch (IOException e) {
                    log.error("加载词典失败", e);
                }
            }
        }
    }

    /**
     * 词典搜索
     *
     * @author leiyuan
     * @since 2025/4/20
     */
    public static List<Map<String, Object>> search(String word) {
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map<String, mdict> mdictMap : mdicts) {
            for (String name : mdictMap.keySet()) {
                mdict md = mdictMap.get(name);
                int search_result = md.lookUp(word, true);//true means to match strictly
                if (search_result >= 0) {
                    try {
                        Map<String, Object> map = new HashMap<>();
                        map.put("name", name.replace(".mdx", ""));
                        map.put("html", md.getRecordAt(search_result));
                        result.add(map);
                    } catch (IOException e) {
                        log.error("加载词典失败", e);
                    }
                }
            }
        }
        return result;
    }
}
